#pragma once

#include<assert.h>

namespace stc
{
	template<class T>
	struct ListNode
	{
		ListNode<T>* _next;
		ListNode<T>* _prev;
		T _data;

		ListNode(const T& x = T())
			:_next(nullptr)
			, _prev(nullptr)
			, _data(x)
		{}
	};

	template<class T>
	struct ListIterator
	{
		typedef  ListNode<T> Node;
		typedef ListIterator<T> Self;

		Node* _node;

		ListIterator(Node* node)
			:_node(node)
		{}

		T& operator*()
		{
			return _node->_data;
		}

		Self& operator++()
		{
			_node = _node->_next;
			return *this;
		}

		Self operator++(int)
		{
			Self tmp(*this);
			_node = _node->_next;

			return tmp;;
		}

		Self& operator--()
		{
			_node = _node->_prev;

			return *this;;
		}

		Self operator--(int)
		{
			Self tmp(*this);
			_node = _node->_prev;

			return tmp;
		}

		bool operator!=(const Self& it)
		{
			return _node != it._node;
		}
		bool operator==(const Self& it)
		{
			return _node == it._node;
		}
		

	};

	template<class T>

	class list
	{
		typedef ListNode<T> Node;

	public:
		typedef ListIterator<T> iterator;

		void empty_init()
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;

			_size = 0;
		}

		list()
		{
			empty_init();
		}

		list(const list<T>& lt)
		{
			empty_init();

			for (aoto& e : lt)
			{
				push_back(a);
			}
		}

		~list()
		{
			clear();
			delete _head;
		}

		void clear()
		{
			iterator it = begin();
			while (it != end())
			{
				it = erase(it);
			}
		}

		void swap(list<T>& lt)
		{
			std::swap(_head, lt._head);
			std::swap(_size, lt._size);

		}

		void push_back(const T& x)
		{
			Node* l = new Node(x);

			l->_prev = _head->_prev;
			_head->_prev->_next = l;
			l->_next = _head;
			_head->_prev = l;

			_size++;
		}

		void insert(iterator pos, const T& val)
		{
			Node* cur = pos._node;
			Node* newnode = new Node(val);
			Node* prev = cur->_prev;

			// prev newnode cur;
			prev->_next = newnode;
			newnode->_prev = prev;
			newnode->_next = cur;
			cur->_prev = newnode;

			_size++;
		}

		iterator erase(iterator pos)
		{
			Node* cur = pos._node;
			Node* prev = cur->_prev;
			Node* next = cur->_next;

			prev->_next = next;
			next->_prev = prev;

			delete cur;

			_size--;

			return iterator(next);
		}

		void push_front(const T& x)
		{
			insert(begin(), x);
			_size++;
		}

		void pop_back()
		{
			erase(--end());
			_size--;
		}

		size_t size()const
		{
			return _size;
		}

		bool empty()
		{
			return _size == 0;
		}

		iterator begin()
		{
			return iterator(_head->_next);
		}

		iterator end()
		{
			return iterator(_head);
		}


	private:
		Node* _head;

		size_t _size;
	};

	void test_l()
	{
		list<int> lt;
		lt.push_back(1);
		lt.push_back(2);
		lt.push_back(3);
		lt.push_back(4);
		lt.push_back(5);

		lt.push_front(0);

		lt.pop_back();

		list<int>::iterator it = lt.begin();

		while (it != lt.end())
		{
			cout << *it << ' ';
			it++;
		}
	}
}
